/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.ifrs.poa.control;

import br.edu.ifrs.poa.database.DBConnection;
import br.edu.ifrs.poa.util.MailSender;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import javax.mail.MessagingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author karenborges
 */
public class ComandoServlet extends HttpServlet {

    private Hashtable comandos;
    private String username;
    private String password;
    private String host;
    private String porta;

    /**
     * Inicialização da Servlet
     * @param config
     * @throws ServletException 
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // Cadastra os comandos
        comandos = new Hashtable();
        comandos.put("cadastroNoticia", "br.edu.ifrs.poa.control.CadastroNoticiaProcessor");
        comandos.put("cadastroUsuario", "br.edu.ifrs.poa.control.CadastroUsuarioProcessor");
        comandos.put("lerNoticia", "br.edu.ifrs.poa.control.LeitorProcessor");
        comandos.put("login", "br.edu.ifrs.poa.control.LoginProcessor");
        comandos.put("menu", "br.edu.ifrs.poa.control.MenuProcessor");

        //Recupera o contexto da aplicação para inicializar o banco de dados
        try {
            ServletContext context = getServletContext();
            String user = (String) context.getInitParameter("user");
            String senha = (String) context.getInitParameter("senha");
            String driver = (String) context.getInitParameter("driver");
            String url = (String) context.getInitParameter("url");
            Connection conexao = DBConnection.getInstance(user, senha, driver, url);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

        //Recupera as informações da servlet
        username = config.getInitParameter("user");
        password = config.getInitParameter("senha");
        host = config.getInitParameter("host");
        porta = config.getInitParameter("porta");
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String cmd = request.getParameter("cmd");
        String actionClass = (String) comandos.get(cmd);
        try {
            //Cria a instância da classe utilizando introspecção
            Processor action = (Processor) Class.forName(actionClass).newInstance();
            action.setRequest(request);
            action.setResponse(response);
            action.setServletContext(getServletContext());
            action.execute();
        } catch (Exception ex) {
            try {
                // TODO revisar o funcionamento do MailSender
                MailSender email = new MailSender(this.username, this.password, this.host, this.porta);
                email.sendMail("Erro no comando " + cmd, ex.getMessage());
                out.println("<h1> Ocorreu um erro.<br> O administrador do sistema já foi notificado através de email. </h1>");
            } catch (MessagingException ex1) {
                throw new ServletException(ex1);
            }
        } finally {
            out.close();
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        try {
            DBConnection.closeConnection();
        } catch (SQLException ex) {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
